package org.runecore.file.io.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import org.runecore.Launch;
import org.runecore.file.io.AbstractFileOperation;
import org.runecore.rs2.model.player.Player;
import org.runecore.rs2.net.sql.SQLConnection;

/**
 * RuneCore
 * Oct 16, 2011
 * @author Harry Andreas<Harry@RuneCore.org>
 * @author Matt Bishop<davidcntt@hotmail.com>
 */
public class SQLPlayerFileOperation extends AbstractFileOperation {

	@Override
	public boolean save(Object... args) {
		try {
			SQLConnection sql = Launch.getEnv().getConnection("player");
			Player p = (Player) args[0];
			String username = p.getUsername().replaceAll(" ", "_").toLowerCase();
			PreparedStatement ps = null;
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(output);
			oos.writeObject(p);
			oos.flush();
			oos.close();
			output.close();
			Statement s = sql.getConnection().createStatement();
			s.executeQuery ("SELECT null FROM players WHERE playerName = '" + username + "' limit 1");
			ResultSet rs = s.getResultSet();
			if (!rs.next()) {
				ps = sql.getConnection().prepareStatement("INSERT INTO players (playerName, password, playerData) VALUES(?, ?, ?)");
				ps.setString(1, username);
				ps.setString(2, p.getPassword());
				ps.setBytes(3, output.toByteArray());
			} else {
				ps = sql.getConnection().prepareStatement("UPDATE players SET playerData = ? WHERE playerName = ?");
				ps.setObject(1, output.toByteArray());
				ps.setString(2, username);
			}
			ps.executeUpdate();
			ps.close();
			return true;
		} catch(Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public Object load(Object... args) {
		Player data = null;
		SQLConnection sql = Launch.getEnv().getConnection("player");
		String username = (String) args[0];
		username = username.replaceAll(" ", "_").toLowerCase();
		try {
			ByteArrayInputStream bais;
			ObjectInputStream ins;
			PreparedStatement ps;
			ps = sql.getConnection().prepareStatement("SELECT * FROM players WHERE playerName = ? LIMIT 1");
			ps.setString(1, username);
			ResultSet results = ps.executeQuery();
			if (results.next()) {
				bais = new ByteArrayInputStream(results.getBytes("playerData"));
				ins = new ObjectInputStream(bais);
				data = (Player) ins.readObject();
				ins.close();
				bais.close();
			}
			ps.close();
		} catch (Exception e) {
			return null;
		}
		return data;
	}

}